'use strict';

import axios from 'axios';
import Cookies from 'js-cookie';
import {store} from '../main.js';
import {router} from '../router/index';
import {Message} from 'iview';
import env from '../../build/env';
import config from '../config/config.json';
import _ from 'lodash'

let Ajax = {};

const apiUrl = getApiBaseUrl();
// 后台服务接口
Ajax.BASE_URL = apiUrl.baseUrl;

// 创建axios实例
Ajax.ajax = axios.create({
    baseURL: Ajax.BASE_URL,
    timeout: 5000
});

// request 拦截器
Ajax.ajax.interceptors.request.use(config => {
    // 发送请求前，统一加上token
    // if (store.getters.token) {    TODO 用这个方式存token，刷新页面会丢失
    //     config.headers['Authorization'] = 'Bearer ' + store.getters.token;
    // }
    if (Cookies.get('user')) {
        const user = JSON.parse(Cookies.get('user'));
        if (user && user.token) {
            config.headers['Authorization'] = 'Bearer ' + user.token;
        }
    }
    return config;
}, error => {
    console.log(error);
    Promise.reject(error);
});

Ajax.ajax.interceptors.response.use(
    response => new Promise((resolve, reject) => {
        let data = response.data
        if (data && data.code !== undefined) {
            switch (data.code) {
                case 0:
                    resolve(data)
                    break
                case 1002:
                    store.commit('logout', this);
                    router.push({name: 'login'});
                default:
                    reject(data)
                    break
            }
        } else {
            reject(data)
        }
    }),
    error => {
        console.log(error);// for debug
        Message.error(error.message);
    });

function getApiBaseUrl() {
    let rst = {"baseUrl": '', "recogUrl": ''}
    if (env === 'production') {
        const host = window.location.host;
        const localIP = host.split(':')[0];

        if (config.api_host.ip === '127.0.0.1' || config.api_host.ip === 'localhost') {
            rst.baseUrl = `http://${localIP}:${config.api_host.port}`;
        } else {
            rst.baseUrl = `http://${config.api_host.ip}:${config.api_host.port}`;
        }
    }
    return rst;
}

function json2Str(data) {
    let dataStr = ''
    _.keys(data).forEach(key => {
        dataStr += `${key}=${data[key]}&`
    })
    if (dataStr !== '') {
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
    }
    return dataStr
}

export default {
    post(url, data) {
        return Ajax.ajax({
            url: url,
            data: data,
            method: 'post'
        })
    },
    get(url, data) {
        let dataStr = json2Str(data)
        url = `${url}?${dataStr}`
        return Ajax.ajax({
            url: url,
            method: 'get'
        })
    }

}